<template>
  <div class="authority">
    <el-form :inline="true" :model="searchInfo" ref='form' class="demo-form-inline">
        <el-form-item label="角色编码" prop="authorityId">
          <el-input placeholder="搜索条件" v-model="searchInfo.authorityId" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="authority_name">
          <el-input placeholder="搜索条件" v-model="searchInfo.authority_name" clearable></el-input>
        </el-form-item>
            <el-form-item label="状态" prop="status">
            <el-select v-model="searchInfo.status" clearable placeholder="请选择">
                <el-option
                   v-for="dict in statusOptions"
                   :key="dict.item_value"
                   :label="dict.item_name"
                   :value="dict.item_value"
                />
            </el-select>
            </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" icon="el-icon-search" type="primary">查询</el-button>
        </el-form-item>
      </el-form>
    <el-form>
        <el-form-item>
          <el-button @click="createAuthority('0')" type="primary">新增角色</el-button>
        </el-form-item>
     </el-form>
    <el-table :data="tableData" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" border row-key="authorityId" stripe style="width: 100%">
      <el-table-column label="角色编码" min-width="180" prop="authorityId"></el-table-column>
      <el-table-column label="角色名称" min-width="150" prop="authority_name"></el-table-column>
      <el-table-column label="状态" min-width="150">
        <template slot-scope="scope">{{scope.row.status|formatString}}</template>
      </el-table-column>
      <el-table-column label="备注" min-width="150" prop="remark"></el-table-column>
      <el-table-column label="创建时间" width="340">
         <template slot-scope="scope">{{scope.row.CreatedAt|formatDate}}</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="260">
        <template slot-scope="scope">
          <el-button @click="opdendrawer(scope.row)" size="small" type="primary">设置权限</el-button>
          <el-button
            @click="updateAuthority(scope.row)"
            icon="el-icon-edit"
            size="small"
            type="primary"
          >编辑</el-button>
          <el-button
            @click="deleteAuth(scope.row)"
            icon="el-icon-delete"
            size="small"
            type="danger"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="page"
      :page-size="pageSize"
      :page-sizes="[10, 30, 50, 100]"
      :style="{float:'right',padding:'20px'}"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 新增角色弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="600px">
      <el-form :model="form" :rules="rules" ref="authorityForm" label-width="110px">
        <el-form-item label="角色编码" prop="authorityId">
          <el-input :disabled="dialogType=='update'" autocomplete="off" v-model="form.authorityId" style="width: 90%"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="authority_name">
          <el-input autocomplete="off" v-model="form.authority_name" style="width: 90%"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.item_value"
                  :label="dict.item_value |formatBoolean"
                >{{ dict.item_name }}</el-radio>
              </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input autocomplete="off" v-model="form.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button @click="enterDialog" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <el-drawer :visible.sync="drawer" :with-header="false" size="40%" title="角色配置" v-if="drawer">
      <el-tabs :before-leave="autoEnter" class="role-box" type="border-card">
        <el-tab-pane label="角色菜单">
          <Menus :row="activeRow" ref="menus" />
        </el-tab-pane>
        <el-tab-pane label="角色api">
          <apis :row="activeRow" ref="apis" />
        </el-tab-pane>
        <el-tab-pane label="项目权限">
              <projectAuth  :row="activeRow" ref="projectAuth" />
          </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </div>
</template>

<script>
// 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成

import {
  getAuthorityList,
  deleteAuthority,
  createAuthority,
  updateAuthority,
} from "@/api/authority";

import Menus from "@/view/superAdmin/authority/components/menus";
import Apis from "@/view/superAdmin/authority/components/apis";
import { formatTimeToStr } from "@/utils/date";
import infoList from "@/mixins/infoList";
import projectAuth from "@/view/superAdmin/authority/components/projectAuth";
export default {
  name: "Authority",
  mixins: [infoList],
  data() {
    return {
      statusOptions: [],
      listApi: getAuthorityList,
      drawer: false,
      dialogType: "add",
      activeRow: {},
      activeUserId: 0,
      dialogTitle: "新增角色",
      dialogFormVisible: false,
      apiDialogFlag: false,
      searchInfo: {
        authorityId: undefined,
        authority_name: undefined,
        status: undefined
      },
      form: {
        authorityId: "",
        authority_name: "",
        remark: "",
        status: true
      },
      rules: {
        authorityId: [
          { required: true, message: "请输入角色编码", trigger: "blur" },
        ],
        authority_name: [
          { required: true, message: "请输入角色名", trigger: "blur" }
        ]
      }
    };
  },
  components: {
    Menus,
    Apis,
    projectAuth
  },
  filters: {
    formatDate: function(time) {
      if (time != null && time != "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
      } else {
        return "";
      }
    },
    formatString: function(bool) {
      if (bool != null) {
        return bool ? "正常" :"关闭";
      } else {
        return "";
      }
    },
    formatBoolean: function(s) {
          if (s == "1" ) {
              return true
          } else {
              return false;
          }
      }
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery(){
        if (this.searchInfo.status==""){
          this.searchInfo.status=null
        }
        this.getTableData()
      },
    /** 权限table */
    autoEnter(activeName, oldActiveName) {
      const paneArr = ["menus", "apis", "projectAuth"];
      if (oldActiveName) {
        if (this.$refs[paneArr[oldActiveName]].needConfirm) {
          this.$refs[paneArr[oldActiveName]].enterAndNext();
          this.$refs[paneArr[oldActiveName]].needConfirm = false;
        }
      }
    },
    /** 设置权限 */
    opdendrawer(row) {
      this.drawer = true;
      this.authorityId = row.authorityId
      this.activeRow = row;
    },
    // 删除角色
    deleteAuth(row) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const res = await deleteAuthority({ authorityId: row.authorityId });
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.getTableData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 初始化表单
    initForm() {
      // if (this.$refs.authorityForm) {
      //   this.$refs.authorityForm.resetFields();
      // }
        this.form = {
            authorityId: "",
            authority_name: "",
            status: true
        };
    },
    // 关闭窗口
    closeDialog() {
      // this.initForm();
      this.dialogFormVisible = false;
      this.apiDialogFlag = false;
    },
    // 确定弹窗
    async enterDialog() {
      if (this.form.authorityId == "0") {
        this.$message({
          type: "error",
          message: "角色id不能为0"
        });
        return false;
      }
      this.$refs.authorityForm.validate(async valid => {
        if (valid) {
          switch (this.dialogType) {
            case "create":
              {
                const res = await createAuthority(this.form);
                if (res.code == 0) {
                  this.$message({
                    type: "success",
                    message: "添加成功!"
                  });
                  await this.getTableData();
                  this.closeDialog();
                }
              }
              break;
            case "update":
              {
                const res = await updateAuthority(this.form);
                if (res.code == 0) {
                  this.$message({
                    type: "success",
                    message: "修改成功!"
                  });
                  await this.getTableData();
                  this.closeDialog();
                }
              }
              break;
          }

          this.initForm();
          this.dialogFormVisible = false;
        }
      });
    },
    setAuthorityOptions(AuthorityData, optionsData, disabled) {
      this.form.authorityId = String(this.form.authorityId);
      AuthorityData &&
        AuthorityData.map(item => {
          if (item.children && item.children.length) {
            const option = {
              authorityId: item.authorityId,
              authorityName: item.authorityName,
              disabled: disabled || item.authorityId == this.form.authorityId,
              children: []
            };
            this.setAuthorityOptions(
              item.children,
              option.children,
              disabled || item.authorityId == this.form.authorityId
            );
            optionsData.push(option);
          } else {
            const option = {
              authorityId: item.authorityId,
              authorityName: item.authorityName,
              disabled: disabled || item.authorityId == this.form.authorityId
            };
            optionsData.push(option);
          }
        });
    },
    // 增加角色
      createAuthority() {
      this.initForm();
      this.dialogTitle = "新增角色";
      this.dialogType = "create";
      this.dialogFormVisible = true;
    },
    // 编辑角色
      updateAuthority(row) {
      this.dialogTitle = "编辑角色";
      this.dialogType = "update";
      this.form = row;
      this.dialogFormVisible = true;
    }
  },
  async created() {
    await this.getTableData();
    this.statusOptions = this.getDicItemList('sys_common_status');
  }
};
</script>
<style lang="scss">
.authority {
  .el-input-number {
    margin-left: 15px;
    span {
      display: none;
    }
  }
  .el-textarea__inner{
       width: 90%;
    }
  .button-box {
    padding: 10px 20px;
    .el-button {
      float: right;
    }
  }
}
.role-box {
  .el-tabs__content {
    height: calc(100vh - 150px);
    overflow: auto;
  }
}
</style>
